package data_structures_and_algorithms.list_node;

import common.ListNode;

/**
 * @ClassName Code_0092_reverseBetweenListNode
 * @Description: https://leetcode.cn/problems/reverse-linked-list-ii/
 * @Author: myl
 * @create_time: 2022/10/27 01:24
 */
public class Code_0092_reverseBetweenListNode {

    // 很容易出错的题目：给要旋转的链表氛围三段，之前 反转的头和尾 之后
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode targetHead = new ListNode(0);
        targetHead.next = head;

        // 找到开始反转的头结点和前一位节点
        ListNode prePart = targetHead;
        for (int i = 0; i < left - 1; i++) {
            prePart = prePart.next;
        }

        // 记录下来要反转的首位节点以及原始尾节点的下一个节点
        int count = right - left + 1;
        ListNode doHead = prePart.next, pre = null, cur = doHead;
        while (cur != null && count > 0){
            ListNode next = cur.next;

            cur.next = pre;
            pre = cur;

            cur = next;
            count--;
        }

        if (cur == null){
            prePart.next = pre;
        }else {
            prePart.next = pre;
            doHead.next = cur;
        }

        return targetHead.next;
    }
}
